package cn.xiaowenjie.services;

import cn.xiaowenjie.beans.QwUser;
import cn.xiaowenjie.boss.form.QueryUserDTO;
import cn.xiaowenjie.boss.form.TDKmanagerForm;
import cn.xiaowenjie.daos.UserManagerDao;
import cn.xiaowenjie.helper.CryptoUtil;
import cn.xiaowenjie.helper.PageTransformer;
import cn.xiaowenjie.response.PageResult;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static cn.xiaowenjie.common.utils.CheckUtil.notNull;

@Service
@Slf4j
public class UserManagerService {
    @Autowired
    private UserManagerDao userManagerDao;

    public PageResult<QwUser> getAll(QueryUserDTO queryUserDTO) {
        // 校验通过后打印重要的日志
        log.info("getAll start ...");
        PageHelper.startPage(queryUserDTO.getPageNo(), queryUserDTO.getPageSize());
        List<QwUser> data = null;
        data = userManagerDao.selectList(queryUserDTO.getName(), queryUserDTO.getPhone(), queryUserDTO.getPosition());
        data.forEach(d -> {
            d.setPassword(CryptoUtil.decode(d.getPassword()));
        });
        log.info("getAll end, data size:" + data.size());
        PageInfo<QwUser> pageInfo = new PageInfo<>(data);
        return PageTransformer.transform(pageInfo);
    }

    /**
     * 增加配置，需要管理员权限
     */
    public void add(QwUser qwUser) {
        // 参数校验
        notNull(qwUser);
        // 校验通过后打印重要的日志
        log.info("add AdvertManager:" + JSON.toJSONString(qwUser));
        //TODO 密码加密
        qwUser.setPassword(CryptoUtil.encode(qwUser.getPassword()));
        userManagerDao.insertSelective(qwUser);
    }

    /**
     * 根据id删除配置项
     * <p>
     * 管理员或者自己创建的才可以删除掉
     */
    public void delete(long id) {
        QwUser user = userManagerDao.selectById(id);
        if (user != null) {
            userManagerDao.deletedById(id);
        }
        // 修改操作需要打印操作结果
        log.info("delete AdvertManager success, id:" + id);
    }

    public void update(QwUser user) {
        if (user != null && user.getId() > 0) {
            user.setPassword(CryptoUtil.encode(user.getPassword()));
            userManagerDao.updateByIdSelective(user);
        }
    }

    public QwUser queryByUserName(String name) {
        return userManagerDao.queryByUserName(name);
    }
}
